<template>
	<div>
		<v-chart ref="chartRef" style="height: 500px" class="w-full" @rendered="onChartRendered" autoresize />
	</div>
</template>

<script setup lang="ts" name="internalOverviewAnalysis">
import { Session } from '/@/utils/storage';
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { BarChart, CustomChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent, ToolboxComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import params from '/@/utils/params';
use([TooltipComponent, LegendComponent, CanvasRenderer, ToolboxComponent, GridComponent, BarChart, CustomChart]);

const router = useRouter();

const props = defineProps({
	projectId: {
		type: String,
		default: () => null,
	},
	projectName: {
		type: String,
		default: () => null,
	},
	dataList: {
		type: Array,
		default: () => [],
	},
	type: {
		type: Number,
		default: 1,
	},
	isPrint: {
		type: Boolean,
		default: false,
	},
});
const barColor = props.type == 1 ? 'rgba(247, 186, 30, 1)' : 'rgba(59, 213, 246, 1)';
// const colorList = [barColor, 'rgba(22, 93, 255, 1)', 'rgb(159, 219, 29)', 'rgb(0, 0, 0, 0)'];
const colorList = [barColor, 'rgba(255, 0, 0, 1)', 'rgb(159, 219, 29)', 'rgb(0, 0, 0, 0)'];
const getXAxisData = () => {
	return props.dataList?.map((item: any) => (props.type == 1 ? item.yearMonth : item.costTypeName));
};
const getMaxValue = (list: Item[], prop: keyof Item): number | undefined => {
	if (list.length === 0) return undefined;
	return Math.max(...list.map((item) => item[prop] as number));
};

// const result = getMaxValue(list, 'value');
// console.log(result); // 输出: 20
const rawData: any = [];
const getRawData = () => {
	const data1: any = [];
	const data2: any = [];
	const data3: any = [];
	rawData.length = 0;
	const maxCostActual = props.dataList.reduce((max, data) => Math.max(max, data.costActual), Number.MIN_SAFE_INTEGER);
	const maxCostBudget = props.dataList.reduce((max, data) => Math.max(max, data.costBudget), Number.MIN_SAFE_INTEGER);
	// const maxCostActual = getMaxValue(props.dataList, 'costActual');
	// const maxCostBudget = getMaxValue(props.dataList, 'costBudget');
	let m = (maxCostActual > maxCostBudget ? maxCostActual : maxCostBudget) / 100;
	props.dataList?.forEach((item: any) => {
		let costActual = item.costActual;
		if (costActual) {
			let costBudget = item.costBudget ? item.costBudget : 0;
			let costDiff = item.costDiff ? item.costDiff : 0;
			if (costBudget > costActual) {
				data1.push({ value: costActual, costTypeId: item.costTypeId });
				data2.push({ value: costDiff > m ? costDiff - m : 0, costTypeId: item.costTypeId, itemStyle: { color: colorList[3] } });
				data3.push({ value: m, costTypeId: item.costTypeId, itemStyle: { color: colorList[2] } });
			} else {
				data1.push({ value: costBudget, costTypeId: item.costTypeId });
				data2.push({ value: m, costTypeId: item.costTypeId, itemStyle: { color: colorList[1] } });
				data3.push({ value: costDiff > m ? costDiff - m : 0, costTypeId: item.costTypeId, itemStyle: { color: colorList[0] } });
			}
		} else {
			data1.push({ value: 0, costTypeId: item.costTypeId });
			data2.push({ value: 0, costTypeId: item.costTypeId });
			data3.push({ value: 0, costTypeId: item.costTypeId });
		}
	});
	rawData.push(data1);
	rawData.push(data2);
	rawData.push(data3);
};
getRawData();
const grid = {
	left: 100,
	right: 100,
	top: 50,
	bottom: 50,
};
const getSeriesConfig = (d1: any[], d2: any[], d3: any[]) => {
	return [
		{
			name: '实际成本',
			type: 'bar',
			stack: 'total',
			barWidth: '50%',
			color: barColor,
			rotate: 90,
			label: {
				show: false,
			},
			data: d1,
		},
		{
			name: '',
			type: 'bar',
			stack: 'total',
			barWidth: '60%',
			label: {
				show: true,
				formatter: (params: any) => {
					let item: any = props.dataList[params.dataIndex];
					if (item) return item.ratio && item.costBudget < item.costActual ? '超支' + item.ratio?.toFixed(2) + '%' + '\n' + item.costDiff : '';
					else return '';
				},
				position: 'right',
			},
			data: d2,
		},
		{
			name: '',
			type: 'bar',
			stack: 'total',
			barWidth: '60%',
			label: {
				show: true,
				// formatter: (params) => (params.value < 1000 ? '' : '节约' + params.value?.toFixed(2) + '%'),
				formatter: (params: any) => {
					let item: any = props.dataList[params.dataIndex];
					if (item) return item.ratio && item.costActual < item.costBudget ? '节约' + item.ratio?.toFixed(2) + '%' + '\n' + item.costDiff : '';
					else return '';
				},
				position: 'right',
			},
			data: d3,
		},
	];
};
const option = {
	legend: {
		selectedMode: false,
	},
	grid,
	yAxis: {
		type: 'value',
	},
	xAxis: {
		type: 'category',
		data: getXAxisData(),
	},
	series: [],
};

const chartRef = ref<typeof VChart | null>(null); // 定义 chart 的引用
let chartInstance: any = null;

const onChartRendered = () => {
	if (chartRef.value) {
		// 获取 ECharts 实例
		chartInstance = chartRef.value.chart;

		// 绑定点击事件
		chartInstance.on('click', handleChartClick);

		// 绑定其他事件（如鼠标悬停）
		chartInstance.on('mouseover', handleChartHover);
	}
};
// 点击事件处理函数
const handleChartClick = (params: any) => {
	if (props.type != 2) return;
	Session.set('projectName', props.projectName);
	Session.set('costTypeId', params.data.costTypeId);
	router.push('/internal/cost/intProjectCostActual/index');
	// console.log('点击参数:', params.data.costTypeId, props.projectName);
};

// 鼠标悬停事件处理函数
const handleChartHover = (params: any) => {
	// console.log('悬停参数:', params);
};

// 组件销毁前移除事件监听
onBeforeUnmount(() => {
	if (chartInstance) {
		chartInstance.off('click', handleChartClick);
		chartInstance.off('mouseover', handleChartHover);
	}
});

watch(
	() => props.dataList,
	() => {
		getRawData();
		chartRef.value.setOption({}, true); // 清除所有设置
		option.xAxis.data = getXAxisData();
		option.series = getSeriesConfig(rawData[0], rawData[1], rawData[2]);
		chartRef.value.setOption(option, true); // 手动更新图表
		chartRef.value.resize();
	},
	{
		deep: true,
	}
);

onMounted(() => {
	option.series = getSeriesConfig(rawData[0], rawData[1], rawData[2]);
	chartRef.value.setOption(option, true, false); // 手动更新图表
	// chartRef.value.on('click', (params: any) => {
	// 	console.log('params', params);
	// });
});
</script>
